import React, { useState, useEffect, useRef } from 'react';
import { NavBar } from 'antd-mobile';
import { Button, message } from 'antd';
import './index.less';
import { history } from 'umi';
import TIM from 'tim-js-sdk';
import TIMUploadPlugin from 'tim-upload-plugin';
import getTimeS from './times';
let options = {
  SDKAppID: 1400804136, // 即时通信IM 应用的 SDKAppID
};
let tim = TIM.create(options);
tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
tim.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
let pdata = JSON.parse(sessionStorage.getItem('userdata'));
//初始化上次显示的时间戳
let lastmessageTime = 0;

export default function index() {
  const [messageApi, contextHolder] = message.useMessage();
  // const [nid,setnid]=useState()
  let nid = '';
  let alist = [];
  const [isCompleted, setisCompleted] = useState('');
  //初始化消息列表
  const [messagelist, setmessagelist] = useState([]);
  const [isShow, setisShow] = useState(true);
  // 对方已读时调用
  let onMessageModified = function (event) {
    agetMessageList();
  };
  // 监听对方是否阅读
  tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, onMessageModified);

  // 接收到消息调用的函数
  let onMessageReceived = function (event) {
    // console.log(event.data[0], '接收消息啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊');
    setmessagelist([...messagelist, event.data[0]]);
    // 在页面内接受的数据直接变已读
    tim.setMessageRead({
      conversationID: history.location.state.conversationID, //用户id
    });
    //页面滚动到底部
    setTimeout(() => {
      allref.current.scrollTo(0, allref.current.scrollHeight);
    }, 1000);
  };
  // 监听对方发送消息
  tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);

  // 定义ref绑定到消息显示dom
  let allref = useRef();
  useEffect(() => {
    // 登录
    let promise = tim.login({
      userID: pdata.userID,
      userSig: pdata.userSig,
    });
    setTimeout(() => {
      // 获取信息列表获取15条默认
      agetMessageList();
    }, 1000);
    // 直接加载到底部
    setTimeout(() => {
      allref.current.scrollTo(0, allref.current.scrollHeight);
      setisShow(false);
    }, 1300);
    window.addEventListener('scroll', huoqu, true);
  }, []);

  const back = () => {
    history.goBack();
  };
  let haha = true;
  let huoqu = async () => {
    if (allref.current.scrollTop == 0 && haha) {
      haha = false;
      let { data } = await tim.getMessageList({
        conversationID: history.location.state.conversationID,
        nextReqMessageID: nid,
      });
      lastmessageTime = data.messageList[0].time * 1000;
      data.messageList.forEach((item) => {
        if (
          lastmessageTime == item.time * 1000 ||
          item.time * 1000 - lastmessageTime > 5 * 60 * 1000
        ) {
          item.isshowtime = true;
          lastmessageTime = item.time * 1000;
        }
      });
      nid = data.nextReqMessageID;
      console.log(messagelist, data.messagelist);
      alist = [...data.messageList, ...alist];
      console.log(alist, 11111111);
      setmessagelist(alist);
      setTimeout(() => {
        haha = true;
      }, 1000);
    }
  };

  // 获取消息列表
  const agetMessageList = async () => {
    let { data } = await tim.getMessageList({
      conversationID: history.location.state.conversationID,
    });
    console.log(data);
    // console.log(data.messageList);
    // 获取到第一条消息的时间作为第一个显示的时间戳
    lastmessageTime = data.messageList[0].time * 1000;
    // 判断距离上一次显示时间戳是否大于五分钟大于添加时间戳并赋值给对应时间
    data.messageList.forEach((item) => {
      if (
        lastmessageTime == item.time * 1000 ||
        item.time * 1000 - lastmessageTime > 5 * 60 * 1000
      ) {
        item.isshowtime = true;
        // console.log('添加了时间戳1111111111111111111111111111');

        lastmessageTime = item.time * 1000;
      }
    });
    nid = data.nextReqMessageID;
    setisCompleted(data.isCompleted);
    setmessagelist(data.messageList);
    alist = data.messageList;
  };
  // 初始化消息变量
  const [words, setwords] = useState('');
  const onChange = (e) => {
    setwords(e.target.value);
  };
  // 发送消息函数
  const publick = () => {
    // 1. 创建消息实例，接口返回的实例可以上屏
    console.log(words.trim());
    if (words.trim().length > 0) {
      //to发送给谁conversationType： C2C个人消息 text消息内容
      let message = tim.createTextMessage({
        to: history.location.state.userProfile.userID,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
          text: words,
          // file: document.getElementById('testPasteInput'),
        },
        needReadReceipt: true,
      });
      // 发送消息
      let promise = tim.sendMessage(message);
      promise
        .then(function (imResponse) {
          // 发送成功
          // console.log(imResponse, '发送成功了》》》》》》》》》》》》');
          // 添加到底部
          setmessagelist([...messagelist, message]);
          allref.current.scrollTo(0, allref.current.scrollHeight);
        })
        .catch(function (imError) {
          // 发送失败
          // console.warn('sendMessage error:', imError);
        });
      // 清空消息框
      setwords('');
    } else {
      alert('请勿发送空消息');
      // messageApi.info('Hello, Ant Design!');
    }
  };
  const checkEnter = () => {
    var e = window.event;
    if (e.keyCode == '13' && e.ctrlKey) {
      // 换行
      setwords(words + '\n');
      return false;
    } else if (e.keyCode == 13) {
      // 发送消息
      publick();
      // 取消默认事件
      e.preventDefault();
    }
    // handle.focus();
  };
  return (
    <div className="kefu">
      {isShow ? <div className="alllook"></div> : ''}
      <NavBar onBack={back}>
        {/* 获取传递过来的信息 */}
        <img src={history.location.state.pdata.face} />
        {history.location.state.pdata.nickname}
      </NavBar>
      <div ref={allref} className="allmessage">
        {messagelist.length > 0 ? (
          <div>
            {messagelist.map((item, index) => (
              <>
                {/* 时间戳显示 */}
                {item.isshowtime ? (
                  <p style={{ textAlign: 'center' }}>
                    {getTimeS(item.time * 1000, true)}
                  </p>
                ) : (
                  ''
                )}
                <div className="amessage" key={index}>
                  {/* <div> */}
                  {item.from == pdata.userID ? (
                    <img className="myface" src={pdata.face} alt="" />
                  ) : (
                    <img
                      className="hitface"
                      src={history.location.state.pdata.face}
                    ></img>
                  )}
                  <span
                    className={item.from == pdata.userID ? 'myname' : 'hitname'}
                  >
                    {item.from}
                  </span>

                  <p
                    className={
                      item.from == pdata.userID ? 'mymessage' : 'hitmessage'
                    }
                  >
                    {/* 已读未读显示 */}
                    {item.isPeerRead ? (
                      <span className="isread">已读</span>
                    ) : (
                      <span className="isread">未读</span>
                    )}

                    {item.payload.text}
                  </p>
                  {/* </div> */}
                </div>
              </>
            ))}
          </div>
        ) : (
          ''
        )}
      </div>
      <div
        style={{
          borderTop: ' 1px solid rgba(81, 78, 78,0.2)',
          backgroundColor: 'white',
        }}
      >
        <textarea
          name=""
          id=""
          value={words}
          onChange={onChange}
          // onKeyDown={()=>{console.log(11)}}
          className="messageinput"
          onKeyDown={checkEnter}
        ></textarea>
        {/* <input type="text" value={words} onChange={onChange}  className="messageinput"/> */}
        <button onClick={publick} className="tohis">
          发送(en)
        </button>
      </div>
    </div>
  );
}
